package com.firefly.web.handle;

import com.firefly.util.handle.CommonResult;
import com.firefly.util.handle.FireflyException;
import com.firefly.util.utils.ResultUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * 捕获异常的类，返回信息给浏览器，可以自定义返回的code,msg等信息
 */

@ControllerAdvice
@Slf4j
public class ExceptionHandle {

    @ExceptionHandler(value = Exception.class)
    @ResponseBody
    public CommonResult handle(Exception e) {
        // 自定义的异常
        if (e instanceof FireflyException) {
            return ResultUtil.validator(((FireflyException) e).getCode(),((FireflyException) e).getErrMsg());
        }else if (e instanceof BindException) {
            // 处理校验失败异常
            BindException eb = (BindException) e;
            String message = eb.getBindingResult().getFieldError().getDefaultMessage();
            return ResultUtil.validator(400,"数据验证失败: " + message);
        }else{
//            log.debug("错误：" + e.toString());
            return ResultUtil.error(500,e.toString());
        }
    }


}